import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { materialTableService } from '../services/UpdateTableService';
import { materialTableConfig } from '../mconfig';
import { Button, Col, Row, Space, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ILoadMapTypeAll } from '@/common';
import { AssetAcquisitionManageAPI } from '../common/type';
import { SelectAssetView } from '../mview/SelectAssetView';

export const OpenMaterialModal: React.FC<AssetAcquisitionManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal, modalType, applyStorageId }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);
  const styleFixCls = 'contract-styfixcls-';
  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);

  /** 获取上下文 */
  const {
    materielList,
    curRes,
    selectType,
    rightTableProps: { materielForm },
    acquisitionDispatch,
    handleAssetVisible,
  } = useContext(AcquisitionManageContext);
  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes, modalType, applyStorageId);

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    // 选择的数据  进行回显
    setCheckMaterialList(materielList);
  }, [isShowModal]);

  /** 点击确定 */
  const onSave = () => {
    // 根据选择的数据更新list
    if (checkMaterialList && checkMaterialList?.length > 0) {
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: checkMaterialList,
      });
      onCloseModalCommon(updateModalRef);
    } else {
      message.warning('请至少选择一条数据');
    }
  };

  // 点击材料入库
  const handleStuffSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: checkMaterialList,
      });
      onCloseModalCommon(updateModalRef);
    } else {
      message.warning('请至少选择一个材料');
    }
  };

  // 点击资产入库
  const handleAssetSave = () => {
    const isChose = checkMaterialList && checkMaterialList?.length > 0 && checkMaterialList?.length < 2;
    if (isChose) {
      // 选择一个资产，弹窗选择资产类型，并填写补充资产信息
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: checkMaterialList,
      });
      handleAssetVisible('add');
      // onCloseModalCommon(updateModalRef);
    } else {
      message.warning('资产入库单次只能选择一个');
    }
  };

  // 弹窗框底部操作
  const renderFooter = () => {
    return (
      <div>
        <Space>
          <Button onClick={handleStuffSave}>材料入库</Button>
          <Button onClick={handleAssetSave}>资产入库</Button>
        </Space>
      </div>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'选择列表'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        onOk={onSave}
        // footer={renderFooter()}
      >
        <UpdateTableCommon
          styleFixCls={styleFixCls}
          searchProps={{
            searchList: [],
            onReset,
            onSearch,
          }}
          selectTablePorps={{
            onSelectTable,
            selectRowObjList: checkMaterialList,
            selectType: 'checkbox',
            setCheckRows: setCheckMaterialList,
            getCheckboxProps: (record: any) => {
              return {
                // disabled: !record.selectFlag,
              };
            },
          }}
          tableProps={{
            columns: materialTableConfig(),
            loading,
            dataSource: data?.rows,
            pagination,
            onPageChange,
            rowKey: 'id',
            tableTotalShow: (total: any, range: any) => {
              return (
                <div
                  style={{
                    display: 'flex',
                    width: '100%',
                    justifyContent: 'space-between',
                  }}
                >
                  <div>
                    已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条材料
                  </div>
                  <div>{showTotalInfo(total, range)}</div>
                </div>
              );
            },
          }}
        />
      </OneModal>
    </>
  );
};
